import { getLocalHistories } from '@/utils/storage';

const initialState = {
  suggestion: [] as string[],
  // 定义保存搜索历史得变量
  // histories: [] as string[],
  histories: getLocalHistories(),
  result: [] as SearchResultType[],
};
// ActionType  就算是type与payload
export type SearchActionType =
  | {
      type: 'search/saveList';
      payload: string[];
    }
  | {
      type: 'search/clearList';
    }
  | {
      type: 'search/saveHistory';
      payload: string;
    }
  | { type: 'search/clearHistories' }
  | { type: 'search/saveResults'; payload: SearchResultType[] }
  | { type: 'search/clearResults' };

// 自动补全类型
export default function Search(
  state = initialState,
  action: SearchActionType
): typeof initialState {
  switch (action.type) {
    case 'search/saveList':
      return {
        ...state,
        suggestion: action.payload,
      };
    case 'search/clearList':
      return {
        ...state,
        suggestion: [],
      };
    case 'search/saveHistory':
      // 去重
      const newList = state.histories.filter((item) => item !== action.payload);
      return {
        ...state,
        histories: [action.payload, ...newList],
      };
    case 'search/clearHistories':
      return {
        ...state,
        histories: [],
      };
    case 'search/saveResults':
      return {
        ...state,
        result: [...state.result, ...action.payload],
      };
    case 'search/clearResults':
      return {
        ...state,
        result: [],
      };
    default:
      return state;
  }
}

export type SearchResultType = {
  art_id: string;
  aut_id: string;
  aut_name: string;
  collect_count: number;
  comm_count: number;
  cover: {
    type: number;
    images: string[]; //有的没有images
  };
  like_count: number;
  pubdate: string;
  title: any;
};
// type SearchResultType = {
//   art_id: string;
//   title: string;
//   aut_id: string;
//   aut_name: string;
//   comm_count: number;
//   pubdate: string;
//   cover: {
//     type: number;
//     images: string[];
//   };
//   like_count: number;
//   collect_count: number;
// };
